//
//  ViewController.m
//  TourDeGarde
//
//  Created by Edenyorke on 14/12/11.
//  Copyright (c) 2011 Edenyorke. All rights reserved.
//

#import "ViewController.h"
#import "MenuTabBarController.h"
#import "MessageUtils.h"
#import "DateUtils.h"
#import "Custody.h"
@implementation ViewController

@synthesize datePicker;
@synthesize dateLabel;
@synthesize menuTabBarController;
@synthesize messageUtils;
@synthesize dateUtils;



- (void)viewDidLoad
{
    [super viewDidLoad];
    messageUtils =  [[MessageUtils alloc] init];
    dateUtils = [[DateUtils alloc]initWithHours ];
    [self initParameters];
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}


-(void)showMenu{
    menuTabBarController = [[MenuTabBarController alloc] init];
    [self presentModalViewController:menuTabBarController animated:YES];
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)getSelection {
    NSDate *pickerDate = [datePicker date];
    NSString *result = [self isDateThisWeek:pickerDate];
    if (result != nil){
        dateLabel.text = result;
    }

}



- (void)viewDidUnload {
    appLabel = nil;
    imageView = nil;
    buttonAction = nil;
    datePicker = nil;
    dateLabel = nil;
    menuTabBarController = nil;
    messageUtils = nil;
    dateUtils = nil;
    imageView = nil;
    
}


- (NSString *) isDateThisWeek:(NSDate *)date {
    
    
    NSDate *start = [[NSDate alloc] init];
    NSDate *end = [[NSDate alloc] init];
    NSString *dateDebutSettings =  [messageUtils getLabel:@"dateDebut"];
    if (dateDebutSettings == nil || [dateDebutSettings isEqualToString:@""]){
        return NSLocalizedString(@"Main.label.error", @"");
    }else{
        start = [dateUtils getDateFromString:dateDebutSettings];
        
    }
    
    NSString *dateFinSettings = [messageUtils getLabel:@"dateFin"]; 
    if (dateFinSettings == nil || [dateFinSettings isEqualToString:@""]){
        return NSLocalizedString(@"Main.label.error", @"");
    }else{
        end = [dateUtils getDateFromString:dateFinSettings];
        
    }
    
    
    
    NSString *periodeTypeSettings = [messageUtils getLabel:@"periodeType"];  
    if (periodeTypeSettings == nil || [periodeTypeSettings isEqualToString:@""]){
       return NSLocalizedString(@"Main.label.error", @"");
        
    }
    
    
    NSString *periodeNumberSettings = [messageUtils getLabel:@"periodeNumber"]; 
    if (periodeNumberSettings == nil || [periodeNumberSettings isEqualToString:@""]){
        return NSLocalizedString(@"Main.label.error", @"");
    }
    
    NSDate *today = [[NSDate alloc] init];
    
    
    if ([self compareDate:date fin:today] == 1){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"ErrorPopupTitle", @"")
                                                        message:NSLocalizedString(@"ErrorPopupContent", @"")
                                                       delegate:nil
                                              cancelButtonTitle:@"OK" 
                                              otherButtonTitles:nil];
        [alert show];
        
        return nil;  
    }
    
    //recuperation de la liste des periodes speciales
    NSMutableArray *listCutodies = [messageUtils getArray:@"listCustodies"];
    //Creation du predicate
    NSPredicate *predicate =[NSPredicate predicateWithFormat:@"beginDate <= %@ AND endDate >= %@", date, date];
    //Filtre de la liste des periode en utilisant le predicate
    NSArray *listCutodiesForDate = [listCutodies filteredArrayUsingPredicate:predicate];
    //On ne garde que la periode la plus petite
    if (listCutodiesForDate != nil && [listCutodiesForDate count] > 0){
        NSInteger timeMin = 0;
        Custody *custodySeleted = nil;
        for (int i = 0; i < [listCutodiesForDate count]; i++){
            Custody *custody = [listCutodiesForDate objectAtIndex:i];
            NSLog(@"Custody Hours : %d", [custody timeBetween]);
            NSLog(@"Custody Name : %@", [custody name]);
            if (i == 0){
                timeMin = [custody timeBetween];
                custodySeleted = custody;
            }else{
                if ([custody timeBetween] < timeMin){
                    timeMin = [custody timeBetween];
                    custodySeleted = custody;
                }
            }
        }
        NSLog(@"Custody Name : %@", [custodySeleted name]);
        if ([custodySeleted isActive]){
            [self displayImage:@"isTourDeGarde.png"];   
            return [NSString stringWithFormat:@"%@", NSLocalizedString(@"Main.label.estla", @"")]; 
        }else{
            [self displayImage:@"isNotTourDeGarde.png"];
            return [NSString stringWithFormat:@"%@", NSLocalizedString(@"Main.label.nestpasla", @"")]; 
        }
    }else{
        NSInteger interval = [self getNbDaysBeetweenTwoDate:start lastDate:end];
      
        while ([self compareDate:date fin:end] == -1) {
            end = [self getFuturDate:end periodeTypeEum:periodeTypeSettings periodeNumber:periodeNumberSettings interval:interval];
            start = [self getFuturDate:start periodeTypeEum:periodeTypeSettings periodeNumber:periodeNumberSettings interval:interval];    
        }
        
        BOOL isValid = true;
        if ([self compareDate:date fin:start] == -1 || [self compareDate:date fin:start] == 0){
            isValid = true;
        }else{
            isValid = false;
        }

        BOOL periodeActiveSettings = [messageUtils getBool:@"isActive"];
        if (isValid){
            if(periodeActiveSettings){
                [self displayImage:@"isTourDeGarde.png"];   
                return [NSString stringWithFormat:@"%@", NSLocalizedString(@"Main.label.estla", @"")]; 
            }else{
                [self displayImage:@"isNotTourDeGarde.png"];
                return [NSString stringWithFormat:@"%@", NSLocalizedString(@"Main.label.nestpasla", @"")]; 
            }
        }else{
            if(periodeActiveSettings){
                [self displayImage:@"isNotTourDeGarde.png"]; 
                return [NSString stringWithFormat:@"%@", NSLocalizedString(@"Main.label.nestpasla", @"")]; 
            }else{
                [self displayImage:@"isTourDeGarde.png"];            
                return [NSString stringWithFormat:@"%@", NSLocalizedString(@"Main.label.estla", @"")]; 
            }
        }
    }
    
    return nil;
    
    
}

- (NSInteger) compareDate:(NSDate *)debut fin:(NSDate *) fin{
    
    NSString *dateDebutString = [[NSString alloc] init ];
    dateDebutString = [dateUtils getStringFromDate:debut];
    debut = [dateUtils getDateFromString:dateDebutString];
    
    NSString *dateFinString = [[NSString alloc] init ];
    dateFinString = [dateUtils getStringFromDate:fin];
    fin = [dateUtils getDateFromString:dateFinString];
    
    NSComparisonResult result = [debut compare:fin];
    
    switch (result)
    {
        case NSOrderedAscending: return 1; break;
        case NSOrderedDescending: return -1; break;
        case NSOrderedSame: return 0; break;
        default: return 0; break;
    }
    
}

-(NSDate *) getFuturDate:(NSDate *)date periodeTypeEum:(NSString *)periodeTypeEum periodeNumber:(NSString *) periodeNumber interval:(NSInteger )interval{

    if ([periodeTypeEum isEqualToString:@"WEEK"]){
        return [self addXWeeksToDate:date nbWeeks:periodeNumber];
    }else if ([periodeTypeEum isEqualToString:@"MONTH"]){
        return [self addXMonthToDate:date nbMonths:periodeNumber]; 
        
    }else if ([periodeTypeEum isEqualToString:@"TIME"]){
        return [self addXDaysToDate:date nbDays:periodeNumber interval:interval];
    }
    
    return 0;
}

- (NSDate *) addXWeeksToDate:(NSDate *)date nbWeeks:(NSString *)nbWeeks{
    
    
    int daysToAdd = ([nbWeeks intValue]);
    
    // set up date components
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components  setWeek:daysToAdd];
    
    // create a calendar
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDate *newDate = [gregorian dateByAddingComponents:components toDate:date options:0];
    
    return newDate;
    
    
}

- (NSDate *) addXMonthToDate:(NSDate *)date nbMonths:(NSString *)nbMonths{
    
    
    NSInteger monthsToAdd = [nbMonths intValue];  // or 60 :-)
    
    // set up date components
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setMonth:monthsToAdd];
    
    // create a calendar
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDate *newDate = [gregorian dateByAddingComponents:components toDate:date options:0];
    
    return newDate;
    
    
}

- (NSDate *) addXDaysToDate:(NSDate *)date nbDays:(NSString *)nbDays interval:(NSInteger)interval{
    
    int daysToAdd = [nbDays intValue]*(int)interval;
    
    // set up date components
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setDay:daysToAdd];
    
    // create a calendar
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDate *newDate = [gregorian dateByAddingComponents:components toDate:date options:0];
    
    return newDate;
    
    
}

- (NSInteger) getNbDaysBeetweenTwoDate:(NSDate *)firstDate lastDate:(NSDate*)lastDate{
    
    NSTimeInterval intervalSecond = [lastDate timeIntervalSinceDate:firstDate];
    NSInteger intervalDays = intervalSecond / 86400;
    return intervalDays;
    
}

- (IBAction)getMenu {
    [self showMenu];
}

- (void)initParameters {
    [messageUtils initData];
    [buttonMenu setTitle:NSLocalizedString(@"Main.button.menu", @"")];
    [buttonAction setTitle:NSLocalizedString(@"Main.button.label", @"") forState:UIControlStateNormal];
    [appLabel setText:NSLocalizedString(@"Main.label.app", @"")];
    datePicker.date=[NSDate date];
     
}

- (void)displayImage:(NSString *) name{
     
    UIImage *image = [UIImage imageNamed:name];
    imageView.image = image;    
}

- (void)viewWillAppear:(BOOL)animated {
    [self initParameters];
}


@end
